<template>
  <div class="work-audit-container">
    <!-- 筛选条件 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="filterForm" :inline="true" label-width="80px">
        <el-form-item label="审计时间">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            :shortcuts="dateShortcuts"
          />
        </el-form-item>
        
        <el-form-item label="分公司">
          <el-select v-model="filterForm.companyId" placeholder="请选择分公司" clearable>
            <el-option label="全部" value="" />
            <el-option
              v-for="company in companyList"
              :key="company.id"
              :label="company.name"
              :value="company.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="部门">
          <el-select v-model="filterForm.deptId" placeholder="请选择部门" clearable>
            <el-option label="全部" value="" />
            <el-option
              v-for="dept in deptList"
              :key="dept.id"
              :label="dept.name"
              :value="dept.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="业务员">
          <el-select
            v-model="filterForm.salesmanId"
            placeholder="请选择业务员"
            clearable
            filterable
          >
            <el-option label="全部" value="" />
            <el-option
              v-for="salesman in salesmanList"
              :key="salesman.id"
              :label="salesman.name"
              :value="salesman.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="工作类型">
          <el-select v-model="filterForm.workType" placeholder="请选择工作类型" clearable>
            <el-option label="全部" value="" />
            <el-option label="客户拜访" value="visit" />
            <el-option label="电话沟通" value="call" />
            <el-option label="合同签署" value="contract" />
            <el-option label="售后服务" value="service" />
            <el-option label="培训学习" value="training" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="审计状态">
          <el-select v-model="filterForm.auditStatus" placeholder="请选择审计状态" clearable>
            <el-option label="全部" value="" />
            <el-option label="待审计" value="pending" />
            <el-option label="审计中" value="auditing" />
            <el-option label="已通过" value="passed" />
            <el-option label="需整改" value="rejected" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleFilter" :loading="loading">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button type="success" @click="handleBatchAudit" :disabled="selectedRows.length === 0">
            <el-icon><Check /></el-icon>
            批量审计
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计概览 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="4">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-icon total">
              <el-icon><DataAnalysis /></el-icon>
            </div>
            <div class="stats-content">
              <div class="stats-value">{{ statsData.totalRecords }}</div>
              <div class="stats-label">总记录数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-icon pending">
              <el-icon><Clock /></el-icon>
            </div>
            <div class="stats-content">
              <div class="stats-value">{{ statsData.pendingRecords }}</div>
              <div class="stats-label">待审计</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-icon auditing">
              <el-icon><View /></el-icon>
            </div>
            <div class="stats-content">
              <div class="stats-value">{{ statsData.auditingRecords }}</div>
              <div class="stats-label">审计中</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-icon passed">
              <el-icon><CircleCheck /></el-icon>
            </div>
            <div class="stats-content">
              <div class="stats-value">{{ statsData.passedRecords }}</div>
              <div class="stats-label">已通过</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-icon rejected">
              <el-icon><CircleClose /></el-icon>
            </div>
            <div class="stats-content">
              <div class="stats-value">{{ statsData.rejectedRecords }}</div>
              <div class="stats-label">需整改</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-icon rate">
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="stats-content">
              <div class="stats-value">{{ (statsData.passRate * 100).toFixed(1) }}%</div>
              <div class="stats-label">通过率</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表分析 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card class="chart-card" shadow="never">
          <template #header>
            <span>审计状态分布</span>
          </template>
          <div ref="statusChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card class="chart-card" shadow="never">
          <template #header>
            <span>工作类型分布</span>
          </template>
          <div ref="typeChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 审计记录表格 -->
    <el-card class="table-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>工作审计记录</span>
          <div class="header-actions">
            <el-button type="success" size="small" @click="handleExport">
              <el-icon><Download /></el-icon>
              导出报告
            </el-button>
            <el-button type="warning" size="small" @click="handleAuditSettings">
              <el-icon><Setting /></el-icon>
              审计设置
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="记录ID" width="80" />
        <el-table-column prop="salesmanName" label="业务员" width="100" />
        <el-table-column prop="companyName" label="分公司" width="120" />
        <el-table-column prop="deptName" label="部门" width="100" />
        <el-table-column prop="workType" label="工作类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getWorkTypeTag(row.workType)">
              {{ getWorkTypeName(row.workType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="workContent" label="工作内容" width="200" show-overflow-tooltip />
        <el-table-column prop="workDate" label="工作日期" width="120" />
        <el-table-column prop="workHours" label="工作时长(h)" width="120" align="center">
          <template #default="{ row }">
            <span class="work-hours">{{ row.workHours?.toFixed(1) || '0.0' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="customerName" label="客户" width="120" />
        <el-table-column prop="location" label="工作地点" width="150" show-overflow-tooltip />
        <el-table-column prop="auditStatus" label="审计状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getAuditStatusTag(row.auditStatus)">
              {{ getAuditStatusName(row.auditStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="auditorName" label="审计人" width="100" />
        <el-table-column prop="auditDate" label="审计时间" width="120" />
        <el-table-column prop="auditRemark" label="审计备注" width="150" show-overflow-tooltip />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleViewDetail(row)">
              详情
            </el-button>
            <el-button 
              v-if="row.auditStatus === 'pending'" 
              type="success" 
              size="small" 
              @click="handleAudit(row)"
            >
              审计
            </el-button>
            <el-button 
              v-if="row.auditStatus === 'rejected'" 
              type="warning" 
              size="small" 
              @click="handleReaudit(row)"
            >
              重审
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 审计对话框 -->
    <el-dialog
      v-model="auditDialogVisible"
      title="工作审计"
      width="600px"
      @close="handleAuditDialogClose"
    >
      <el-form :model="auditForm" :rules="auditRules" ref="auditFormRef" label-width="100px">
        <el-form-item label="审计结果" prop="result">
          <el-radio-group v-model="auditForm.result">
            <el-radio label="passed">通过</el-radio>
            <el-radio label="rejected">需整改</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="审计评分" prop="score">
          <el-rate
            v-model="auditForm.score"
            :max="5"
            show-score
            text-color="#ff9900"
            score-template="{value}分"
          />
        </el-form-item>
        
        <el-form-item label="审计备注" prop="remark">
          <el-input
            v-model="auditForm.remark"
            type="textarea"
            :rows="4"
            placeholder="请输入审计备注"
          />
        </el-form-item>
        
        <el-form-item v-if="auditForm.result === 'rejected'" label="整改要求" prop="requirement">
          <el-input
            v-model="auditForm.requirement"
            type="textarea"
            :rows="3"
            placeholder="请输入整改要求"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="auditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirmAudit" :loading="auditLoading">
          确认审计
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Search, 
  Refresh, 
  Check, 
  Download, 
  Setting, 
  DataAnalysis, 
  Clock, 
  View, 
  CircleCheck, 
  CircleClose, 
  TrendCharts 
} from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import type { FormInstance, FormRules } from 'element-plus'

// 响应式数据
const loading = ref(false)
const auditLoading = ref(false)
const auditDialogVisible = ref(false)
const statusChartRef = ref<HTMLDivElement>()
const typeChartRef = ref<HTMLDivElement>()
const auditFormRef = ref<FormInstance>()

// 筛选表单
const filterForm = reactive({
  dateRange: [],
  companyId: '',
  deptId: '',
  salesmanId: '',
  workType: '',
  auditStatus: ''
})

// 审计表单
const auditForm = reactive({
  id: '',
  result: 'passed',
  score: 5,
  remark: '',
  requirement: ''
})

// 表单验证规则
const auditRules: FormRules = {
  result: [
    { required: true, message: '请选择审计结果', trigger: 'change' }
  ],
  score: [
    { required: true, message: '请给出审计评分', trigger: 'change' }
  ],
  remark: [
    { required: true, message: '请输入审计备注', trigger: 'blur' }
  ]
}

// 分页数据
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 统计数据
const statsData = reactive({
  totalRecords: 0,
  pendingRecords: 0,
  auditingRecords: 0,
  passedRecords: 0,
  rejectedRecords: 0,
  passRate: 0
})

// 表格数据
const tableData = ref([])
const selectedRows = ref([])

// 下拉选项
const companyList = ref([])
const deptList = ref([])
const salesmanList = ref([])

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]

// 图表实例
let statusChart: echarts.ECharts | null = null
let typeChart: echarts.ECharts | null = null

// 方法
const handleFilter = () => {
  pagination.page = 1
  getTableData()
  updateCharts()
}

const handleReset = () => {
  Object.assign(filterForm, {
    dateRange: [],
    companyId: '',
    deptId: '',
    salesmanId: '',
    workType: '',
    auditStatus: ''
  })
  handleFilter()
}

const handleBatchAudit = () => {
  ElMessage.info('批量审计功能开发中')
}

const handleExport = () => {
  ElMessage.success('导出功能开发中')
}

const handleAuditSettings = () => {
  ElMessage.info('审计设置功能开发中')
}

const handleViewDetail = (row: any) => {
  ElMessage.info(`查看工作记录 ${row.id} 的详细信息`)
}

const handleAudit = (row: any) => {
  auditForm.id = row.id
  auditDialogVisible.value = true
}

const handleReaudit = (row: any) => {
  auditForm.id = row.id
  auditDialogVisible.value = true
}

const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  getTableData()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  getTableData()
}

const handleAuditDialogClose = () => {
  auditFormRef.value?.resetFields()
  Object.assign(auditForm, {
    id: '',
    result: 'passed',
    score: 5,
    remark: '',
    requirement: ''
  })
}

const handleConfirmAudit = () => {
  auditFormRef.value?.validate((valid) => {
    if (valid) {
      auditLoading.value = true
      // TODO: 调用审计API
      setTimeout(() => {
        auditLoading.value = false
        auditDialogVisible.value = false
        ElMessage.success('审计完成')
        getTableData()
      }, 1000)
    }
  })
}

const getTableData = async () => {
  loading.value = true
  try {
    // TODO: 调用API获取数据
    setTimeout(() => {
      tableData.value = [
        {
          id: 'WA001',
          salesmanName: '张三',
          companyName: '北京分公司',
          deptName: '销售一部',
          workType: 'visit',
          workContent: '拜访客户李先生，洽谈购房意向',
          workDate: '2024-01-15',
          workHours: 2.5,
          customerName: '李先生',
          location: '朝阳区某小区',
          auditStatus: 'pending',
          auditorName: '',
          auditDate: '',
          auditRemark: ''
        },
        {
          id: 'WA002',
          salesmanName: '李四',
          companyName: '上海分公司',
          deptName: '销售二部',
          workType: 'call',
          workContent: '电话回访客户王女士，跟进合同签署进度',
          workDate: '2024-01-14',
          workHours: 1.0,
          customerName: '王女士',
          location: '公司办公室',
          auditStatus: 'passed',
          auditorName: '审计员A',
          auditDate: '2024-01-15',
          auditRemark: '工作记录完整，客户反馈良好'
        }
      ]
      pagination.total = 150
      
      // 更新统计数据
      Object.assign(statsData, {
        totalRecords: 150,
        pendingRecords: 45,
        auditingRecords: 12,
        passedRecords: 78,
        rejectedRecords: 15,
        passRate: 0.84
      })
      
      loading.value = false
    }, 1000)
  } catch (error) {
    loading.value = false
    ElMessage.error('获取数据失败')
  }
}

const initCharts = () => {
  nextTick(() => {
    if (statusChartRef.value) {
      statusChart = echarts.init(statusChartRef.value)
    }
    if (typeChartRef.value) {
      typeChart = echarts.init(typeChartRef.value)
    }
    updateCharts()
  })
}

const updateCharts = () => {
  updateStatusChart()
  updateTypeChart()
}

const updateStatusChart = () => {
  if (!statusChart) return
  
  const data = [
    { name: '待审计', value: 45 },
    { name: '审计中', value: 12 },
    { name: '已通过', value: 78 },
    { name: '需整改', value: 15 }
  ]
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c}条 ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '审计状态',
        type: 'pie',
        radius: '50%',
        data: data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  statusChart.setOption(option)
}

const updateTypeChart = () => {
  if (!typeChart) return
  
  const data = [
    { name: '客户拜访', value: 65 },
    { name: '电话沟通', value: 45 },
    { name: '合同签署', value: 25 },
    { name: '售后服务', value: 15 }
  ]
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c}条 ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '工作类型',
        type: 'pie',
        radius: ['40%', '70%'],
        data: data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  typeChart.setOption(option)
}

// 工具方法
const getWorkTypeTag = (type: string) => {
  const tagMap: Record<string, string> = {
    visit: 'primary',
    call: 'success',
    contract: 'warning',
    service: 'info',
    training: 'danger'
  }
  return tagMap[type] || 'info'
}

const getWorkTypeName = (type: string) => {
  const nameMap: Record<string, string> = {
    visit: '客户拜访',
    call: '电话沟通',
    contract: '合同签署',
    service: '售后服务',
    training: '培训学习'
  }
  return nameMap[type] || type
}

const getAuditStatusTag = (status: string) => {
  const tagMap: Record<string, string> = {
    pending: 'warning',
    auditing: 'primary',
    passed: 'success',
    rejected: 'danger'
  }
  return tagMap[status] || 'info'
}

const getAuditStatusName = (status: string) => {
  const nameMap: Record<string, string> = {
    pending: '待审计',
    auditing: '审计中',
    passed: '已通过',
    rejected: '需整改'
  }
  return nameMap[status] || status
}

// 初始化数据
const initData = () => {
  companyList.value = [
    { id: '1', name: '北京分公司' },
    { id: '2', name: '上海分公司' },
    { id: '3', name: '广州分公司' }
  ]
  
  deptList.value = [
    { id: '1', name: '销售一部' },
    { id: '2', name: '销售二部' },
    { id: '3', name: '客服部' }
  ]
  
  salesmanList.value = [
    { id: '1', name: '张三' },
    { id: '2', name: '李四' },
    { id: '3', name: '王五' }
  ]
  
  getTableData()
  initCharts()
}

onMounted(() => {
  initData()
})
</script>

<style lang="scss" scoped>
.work-audit-container {
  padding: 20px;
  
  .filter-card {
    margin-bottom: 20px;
  }
  
  .stats-row {
    margin-bottom: 20px;
    
    .stats-card {
      .stats-item {
        display: flex;
        align-items: center;
        
        .stats-icon {
          width: 50px;
          height: 50px;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 12px;
          font-size: 20px;
          color: white;
          
          &.total {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          }
          
          &.pending {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
          }
          
          &.auditing {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
          }
          
          &.passed {
            background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
          }
          
          &.rejected {
            background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
          }
          
          &.rate {
            background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
          }
        }
        
        .stats-content {
          .stats-value {
            font-size: 20px;
            font-weight: bold;
            color: #303133;
            margin-bottom: 3px;
          }
          
          .stats-label {
            font-size: 12px;
            color: #909399;
          }
        }
      }
    }
  }
  
  .chart-row {
    margin-bottom: 20px;
    
    .chart-card {
      .chart-container {
        height: 300px;
      }
    }
  }
  
  .table-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .header-actions {
        display: flex;
        gap: 10px;
      }
    }
    
    .work-hours {
      color: #409eff;
      font-weight: bold;
    }
    
    .pagination-container {
      margin-top: 20px;
      text-align: right;
    }
  }
}
</style>
